package com.dsiab.manageService.controller;

import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import com.dsiab.manageService.common.CommonUtils;
import com.dsiab.manageService.common.ResponseMap;
import com.dsiab.manageService.entity.AccountDto;
import com.dsiab.manageService.entity.SiteInfoDto;
import com.dsiab.manageService.service.AccountService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/account")
public class AccountController {

  @Autowired
  AccountService accountService;
  @Autowired
  CommonUtils commonUtils;

  /**
   * 登录
   */
  @PostMapping("/login")
  public ResponseMap login(@RequestBody AccountDto accountDto, HttpServletRequest request) throws Exception {
    String ip = commonUtils.getIpAddr(request);
    return ResponseMap.success(accountService.login(accountDto,ip));
  }

  /**
   * 退出
   */
  @PostMapping("/logout")
  public ResponseMap logout() {
    // 供springboot security使用
    return ResponseMap.success();
  }

  /**
   * 更新用户信息
   */
  @PostMapping("/updateUserInfo")
  @PreAuthorize("hasRole('ROLE_author')")
  public ResponseMap updateUserInfo(@RequestBody AccountDto accountDto) {
    accountService.updateUserInfo(accountDto);
    return ResponseMap.success();
  }

  /**
   * 更新站点信息
   */
  @PostMapping("/updateSiteInfo")
  @PreAuthorize("hasRole('ROLE_admin')")
  public ResponseMap updateSiteInfo(@RequestBody SiteInfoDto siteInfoDto) {
    accountService.updateSiteInfo(siteInfoDto);
    return ResponseMap.success();
  }

  /**
   * 注册
   */
  @PostMapping("/register")
  public ResponseMap register(@RequestBody Map map) throws Exception {
    try {
      accountService.register(map);
    } catch (Exception e){
      return ResponseMap.error("注册失败，该账号已存在");
    }
    return ResponseMap.success();
  }

  /**
   * 查询用户信息
   */
  @GetMapping("/getUserInfo")
  @PreAuthorize("hasRole('ROLE_author')")
  public ResponseMap getUserInfo() {
    return ResponseMap.success(accountService.getUserInfo());
  }

  /**
   * 文件上传
   */
  @PostMapping("/upload")
  @PreAuthorize("hasRole('ROLE_author')")
  public Map upload(@RequestParam("file") MultipartFile uploadFile) {

    Map map = new HashMap();
    Map siteInfo = accountService.getSiteInfo();
    String realPath = (String) siteInfo.get("sourceRealUrl");
    String sourceUrl = (String) siteInfo.get("sourceUrl");

    // 获取前当天时间
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
    Calendar calendarCurr = new GregorianCalendar();
    calendarCurr.setTime(new Date());
    calendarCurr.add(Calendar.DATE,0);
    String currDate = sdf.format(calendarCurr.getTime());

    File folder = new File(realPath + currDate);
    if (!folder.isDirectory()) {
      folder.mkdirs();
    }
    // 生成唯一名称
    String oldName = uploadFile.getOriginalFilename();
    String newName = oldName;
    // 源文件后缀名
    String originSuffix = oldName.substring(oldName.lastIndexOf("."));
    // 图片压缩后后缀名
    String imgNewSuffix = ".jpg";
    String filePath;
    if (commonUtils.isImg(oldName)){
      // 如果是图片则用uuid替换文件名
      newName = UUID.randomUUID().toString();
    }

    try {
      uploadFile.transferTo(new File(folder, newName + originSuffix));
      filePath = sourceUrl + currDate + "/" + newName + originSuffix;
      // 如果是图片则进行压缩生成jpg格式，hutool目前只支持生成jpg格式
      if (commonUtils.isImg(oldName)) {
        Img.from(FileUtil.file(realPath + currDate + "/" + newName + originSuffix))
                .setQuality(0.3)//压缩比率
                .write(FileUtil.file(realPath + currDate + "/" + newName + imgNewSuffix));
        filePath = sourceUrl + currDate + "/" + newName + imgNewSuffix;
        // 压缩成功删除旧文件
        File file = new File(realPath + currDate + "/" + newName + originSuffix);
        if (file.exists()){
          file.delete();
        }
      }

      ArrayList al = new ArrayList();
      Map fileInfo = new HashMap();
      fileInfo.put("url", filePath);
      fileInfo.put("alt", filePath);
      fileInfo.put("href", filePath);
      al.add(fileInfo);
      map.put("errno", 0);
      map.put("data", al);
      return map;
    } catch (IOException e){
      e.printStackTrace();
    }
    return map;
  }

  /**
   * 校验邮箱是否有效
   */
  @GetMapping("/getValidEmailEffective")
  public ResponseMap getValidEmailEffective(@RequestParam String id) {
    accountService.getValidEmailEffective(id);
    return ResponseMap.success();
  }
}
